package com.wrl.mmall.controller.portal;

import com.wrl.mmall.common.Const;
import com.wrl.mmall.common.ServerResponse;
import com.wrl.mmall.pojo.User;
import com.wrl.mmall.service.IUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;

/**
 * 使用SpringSession管理用户
 * <p>
 * Created by Wang Renlei on 2018/8/22.
 */
@Slf4j
@RestController
@RequestMapping("/user/springsession")
public class UserSpringSessionController {

    @Autowired
    private IUserService iUserService;

    //登陆
    @RequestMapping(value = "login.do")
    public ServerResponse<User> login(String username, String password, HttpSession session) {
        log.info("UserController.login");
        if (StringUtils.isBlank(username) || StringUtils.isBlank(password)) {
            return ServerResponse.createByErrorMessage("必要参数为空");
        }
        ServerResponse<User> user = iUserService.login(username, password);
        if (user.isSuccess()) {
            session.setAttribute(Const.CURRENT_USER, user.getData());
        }
        return user;
    }

    //退出登录
    @RequestMapping(value = "login_out.do", method = RequestMethod.GET)
    public ServerResponse<User> loginOut(HttpSession session) {
        log.info("UserController.loginOut");
        session.removeAttribute(Const.CURRENT_USER);
        return ServerResponse.createBySuccess();
    }

    //获取用户信息
    @RequestMapping(value = "get_user_info.do", method = RequestMethod.GET)
    public ServerResponse<User> getUserInfo(HttpSession session) {
        log.info("UserController.getUserInfo");
        User user = (User) session.getAttribute(Const.CURRENT_USER);
        if (user != null) {
            return ServerResponse.createBySuccess(user);
        }
        return ServerResponse.createByErrorMessage("用户未登录，无法获取信息");
    }

}
